#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <string>
using namespace std;

int ticket = 10000;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void *buy_ticket(void *args)
{
    string name = *reinterpret_cast<string *>(args);
    while (true)
    {
        pthread_mutex_lock(&mutex);
        if (ticket > 0)
        {
            usleep(1000);
            ticket--;
            printf("%s 购票成功，余票: %d\n", name.c_str(), ticket);
            pthread_mutex_unlock(&mutex);
        }
        else
        {
            pthread_mutex_unlock(&mutex);
            break;
        }
    }
    return nullptr;
}

string getname()
{
    static int num = 1;
    string name = "线程-" + to_string(num++);
    return name;
}

int main()
{
    pthread_t t1;
    pthread_t t2;
    pthread_t t3;
    pthread_t t4;
    pthread_create(&t1, nullptr, buy_ticket, new string(getname()));
    pthread_create(&t2, nullptr, buy_ticket, new string(getname()));
    pthread_create(&t3, nullptr, buy_ticket, new string(getname()));
    pthread_create(&t4, nullptr, buy_ticket, new string(getname()));

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    pthread_join(t4, nullptr);
    cout << "等待成功" << endl;
    return 0;
}